package com.jsgt.greekfire.ui.entrust.fragment

import android.text.TextUtils
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseFragment
import com.fhx.core.utils.LogUtils
import com.fhx.core.utils.ToastUtils
import com.google.gson.Gson
import com.google.protobuf.ByteString
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.AtrAccountInfoBean
import com.jsgt.greekfire.common.util.MD5Util
import com.jsgt.greekfire.common.util.XLinearLayoutManager
import com.jsgt.greekfire.dao.model.IdentityBean
import com.jsgt.greekfire.dao.model.IdentityWallet
import com.jsgt.greekfire.dao.viewmodel.WalletViewModel
import com.jsgt.greekfire.event.EntrustEvent
import com.jsgt.greekfire.ui.dialog.InputDialogUtil
import com.jsgt.greekfire.ui.entrust.adapter.MyEntrustAdapter
import com.jsgt.greekfire.viewmodel.EntrustViewModel
import com.jsgt.greekfire.viewmodel.UserViewModel
import com.scwang.smartrefresh.header.MaterialHeader
import kotlinx.android.synthetic.main.fragment_my_entrust.*
import org.altoro.common.crypto.Sha256Sm3Hash
import org.altoro.common.crypto.SignUtils
import org.bouncycastle.util.encoders.Hex
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigInteger

class MyEntrustFragment : BaseFragment() {
    private val entrustViewModel: EntrustViewModel by lazy {
        ViewModelProvider(this).get(EntrustViewModel::class.java)
    }
    private val myEntrustAdapter by lazy {
        MyEntrustAdapter(requireContext(), R.layout.item_my_entrust_list)
    }
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(this).get(UserViewModel::class.java)
    }
    private val walletViewModel: WalletViewModel by lazy {
        ViewModelProvider(this).get(WalletViewModel::class.java)
    }
    private var wallet: IdentityWallet? = null
    private var identityBean: IdentityBean? = null
    private var list: ArrayList<AtrAccountInfoBean.DelegateBean>? = ArrayList();

    override fun getLayoutId(): Int = R.layout.fragment_my_entrust
    override fun main() {
        refreshMyEntrust.autoRefresh()
        refreshMyEntrust.setRefreshHeader(MaterialHeader(context));
        refreshMyEntrust.setOnRefreshListener {
            if (wallet != null) {
                userViewModel.getAccount(wallet?.address!!, "true")
            }
        }
        rvMyEntrust.layoutManager = XLinearLayoutManager(context)
        rvMyEntrust.adapter = myEntrustAdapter
        myEntrustAdapter.addChildClickViewIds(R.id.tvPutEntrust)
        myEntrustAdapter.setOnItemChildClickListener { adapter, view, position ->
            var data = myEntrustAdapter.getItem(position)
            if (view.id == R.id.tvPutEntrust) {
                InputDialogUtil.showInputDialog(
                    requireContext(),
                    getString(R.string.pool_join_password_input),
                    getString(R.string.pool_join_password_input)
                ) {
                    if (!TextUtils.isEmpty(it) && identityBean != null) {
                        //ToastUtils.show("退出委托")
                        if (MD5Util.getMD5(it) == identityBean?.password) {
                            showProgress(true);
                            entrustViewModel.undelegateaccount(
                                wallet?.address!!,
                                data.delegate_address!!,
                                "true"
                            )
                        } else {
                            showToast(getString(R.string.pwd_error))
                        }
                    } else {
                        ToastUtils.show(getString(R.string.pool_join_password_input))
                    }
                }
            }
        }

        entrustViewModel.broadcasttransactionListData.observe(this, Observer {
            showProgress(false)
            try {
                if (it != null) {
                    if (!TextUtils.isEmpty(it.txid)) {
                        EventBus.getDefault().post(EntrustEvent(""))
                        userViewModel.getAccount(wallet?.address!!, "true")
                    }
                }
            } catch (e: Exception) {
                LogUtils.error(e.message)
                e.printStackTrace()
            }
        })

        entrustViewModel.undelegateaccountListData.observe(this, Observer {
            if (it != null && !TextUtils.isEmpty(it.raw_data_hex)) {
                try {
                    val cryptoEngine = SignUtils.fromPrivate(
                        Hex.decode(
                            BigInteger(identityBean?.getPriKeyByAES()).toString(16)
                        ), true
                    )
                    val rawData = Sha256Sm3Hash.of(Hex.decode(it.raw_data_hex))
                    val sig =
                        ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine.signHash(rawData.bytes)))
                    val signature = Hex.toHexString(sig.toByteArray())
                    it.signature = signature
                    var data = Gson()
                    entrustViewModel.broadcasttransaction(data.toJson(it))
                    /*    var privateKey = YTWalletUtils.getPrivateKey(identityBean?.getMnemonicByAES())
                        val rawData = Sha256Sm3Hash.of(Hex.decode(it.raw_data_hex))
                        val sig = ByteString.copyFrom(privateKey.Base64toBytes(privateKey.signHash(rawData.bytes)))
                        val signature = Hex.toHexString(sig.toByteArray())
                        it.signature = signature
                        var data = Gson()
                        entrustViewModel.broadcasttransaction(data.toJson(it))*/
                } catch (e: Exception) {
                    LogUtils.error(e.message)
                    e.printStackTrace()
                }
            }

        })


        walletViewModel.getSelectWallet()?.observe(this, Observer {
            if (it != null && it.isNotEmpty()) {
                wallet = it[0]
                userViewModel.getAccount(wallet?.address!!, "true")

                walletViewModel.getIdentity(wallet!!.identityId)?.observe(this, Observer { it1->
                    if (it1 != null) {
                        identityBean = it1
                    }
                })
            }
        })
        userViewModel.getAccountLiveData.observe(this, Observer {
            if (it != null) {
                if (it.delegate != null && it.delegate!!.size > 0) {
                    myEntrustAdapter.setNewData(it.delegate as MutableList<AtrAccountInfoBean.DelegateBean>?)
                } else {
                    myEntrustAdapter.setNewData(list)
                    myEntrustAdapter.setEmptyView(R.layout.item_entrust_empty)
                }
                if (refreshMyEntrust != null) {
                    refreshMyEntrust.finishRefresh();
                    refreshMyEntrust.finishLoadMore();//不传时间则立即停止刷新    传入false表示加载失败
                    refreshMyEntrust.finishLoadMoreWithNoMoreData();//没有加载更多
                }
            }
        })
        entrustViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
            if (refreshMyEntrust != null) {
                refreshMyEntrust.finishRefresh();
                refreshMyEntrust.finishLoadMore();//不传时间则立即停止刷新    传入false表示加载失败
                refreshMyEntrust.finishLoadMoreWithNoMoreData();//没有加载更多
            }
            ToastUtils.show(it.toString())
        })

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEntrustEvent(e: EntrustEvent) {
        if (wallet != null) {
            userViewModel.getAccount(wallet?.address!!, "true")
        }
    }
}